//
//  Plot+CRUD.m
//  PlotMate
//
//  Created by Brian Boyle on 04/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "Plot+CRUD.h"

@implementation Plot (CRUD)


+(Plot *)createPlotFromTempPlot:(TempPlot *)tempPlot WithContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Plot"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", tempPlot.name];
    
    NSError *error;
    NSArray *existingPlots = [context executeFetchRequest:request error:&error];
    
    if([existingPlots count] == 0){
        Plot *newPlot = [NSEntityDescription insertNewObjectForEntityForName:@"Plot" inManagedObjectContext:context];
        newPlot.name = tempPlot.name;
        newPlot.soilType = tempPlot.soilType;
        newPlot.lightingConditions = tempPlot.lightConditions;
        return newPlot;
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"A plot named %@ already exists, please choose a different name", tempPlot.name] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [errorAlert show];
        return nil;
    }
}

+(BOOL)checkIfPlotsExistInContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Plot"];
    
    NSError *error;
    NSArray *existingPlots = [context executeFetchRequest:request error:&error];
    if([existingPlots count] == 0){
        return NO;
    }
    return YES;
}

+(NSArray *)loadAllPlotsInContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Plot"];
    
    NSError *error;
    return [context executeFetchRequest:request error:&error];
}

@end
